//
//  ZDBGameViewController.m
//  ZDB
//
//  Created by Kk on 2020/3/17.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBGameViewController.h"
#import "ZDBGamePeopleInfoView.h"
#import "ZDBRankListTableViewCell.h"
#import "UILabel+ChangeLineSpaceAndWordSpace.h"
#import "ZDBInviteFriendsViewController.h"

@interface ZDBGameViewController ()
<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UILabel *contentLab;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)NSMutableArray *userInfoArry;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSDictionary * nowDiccInfo;
@property(nonatomic,strong)NSDictionary * infoDicc;
@property (nonatomic, strong) ZDBGamePeopleInfoView * tableHeaderView;
@property (weak, nonatomic) IBOutlet UIView *bgView;

@property (nonatomic,strong) NoNetworkView * workView;

@end

@implementation ZDBGameViewController

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
     self.tableHeaderView.frame = CGRectMake(0, 0, kScreenWidth, 60);
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.userInfoArry = [NSMutableArray array];
    self.dataSource = [NSMutableArray array];
    self.nowDiccInfo = [NSDictionary dictionary];
    self.infoDicc = [NSDictionary dictionary];
    NSDictionary * myDicc = [[DJLoginHelper sharedInstance] cj_UserDicc];
    [self.userInfoArry addObject:myDicc];
    self.nowDiccInfo = myDicc;
    // Do any additional setup after loading the view from its nib.

    [self creat_UI];
    [self creatBtnsList:0];
    
    
    WEAKSELF
       // 上拉加载
       MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
           STRONGSELFFor(weakSelf)
           strongSelf.page =1;
           [strongSelf getuserShareNumberInfo];
           [strongSelf requestDataDicc:self.nowDiccInfo];
       }];
       [header beginRefreshing];
       self.tableView.mj_header = header;
       
       MJRefreshBackStateFooter * foot = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{
           STRONGSELFFor(weakSelf)
            strongSelf.page ++;
            [strongSelf requestDataDicc:self.nowDiccInfo];
       }];
       self.tableView.mj_footer = foot;
    
}

-(void)creat_UI{
    self.view.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    self.tableHeaderView = [[NSBundle mainBundle]loadNibNamed:@"ZDBGamePeopleInfoView" owner:self options:nil].lastObject;
    self.tableHeaderView.frame = CGRectMake(0, 0, kScreenWidth-30, 60);
    self.tableView.tableHeaderView =self.tableHeaderView;
    [self.view addSubview:self.tableView];
    
    self.tableHeaderView.userDicc = self.userInfoArry.lastObject;
       UIButton * reBtn = [UIButton buttonWithType:UIButtonTypeCustom];
         reBtn.frame = CGRectMake(0, -10, 50, 40);
    //     [reBtn setImage:[UIImage imageNamed:@"goBack"] forState:UIControlStateNormal];
        [reBtn setTitle:@"邀请" forState:0];
        [reBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [reBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:0];
         [reBtn addTarget:self action:@selector(reBtnClik) forControlEvents:UIControlEventTouchUpInside];
         reBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
         self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:reBtn];
    
}
-(void)reBtnClik{
    
    ZDBInviteFriendsViewController * vcc = [ZDBInviteFriendsViewController new];
    vcc.title = @"邀请好友";
    vcc.is_Pop =YES;
    [self.navigationController pushViewController:vcc animated:YES];
    
    
    
}
-(void)creatBtnsList:(NSInteger)index{
    [self.bgView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    NSArray * titleArry = @[@"我的下级",@"二级推广",@"三级推广",@"四级推广",];
    
    NSMutableArray * subArry = [NSMutableArray array];
    for (int i = 0; i <= index; i++) {
     
            [subArry addObject:titleArry[i]];
   
    }
    
    CGFloat Start_X    =    15.0f;    // 第一个按钮的X坐标
    CGFloat Width_Space    =  8.0f;    // 2个按钮之间的横间距
    CGFloat Button_Height  =35.0f  ;  // 高
    CGFloat Start_Y        =  12.5;
    CGFloat Button_Width  = 75;  // 宽
    
    for (int j = 0; j < subArry.count; j++) {
        
        UIButton * bbBtn = [BBControl createButtonWithFrame:CGRectMake(j * (Button_Width + Width_Space) + Start_X,  Start_Y, Button_Width, Button_Height)target:self SEL:@selector(bbBtnClick:) title:[NSString stringWithFormat:@"%@ ",titleArry[j]]];
    
        [bbBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [bbBtn setImage:[UIImage imageNamed:@"btn_righticon"] forState:0];
        [bbBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, - bbBtn.imageView.image.size.width, 0, bbBtn.imageView.image.size.width)];
        [bbBtn setImageEdgeInsets:UIEdgeInsetsMake(0, bbBtn.titleLabel.bounds.size.width, 0, -bbBtn.titleLabel.bounds.size.width)];
        [bbBtn setTitleColor:MAINCOLOR forState:0];
        bbBtn.tag = j;
        if (bbBtn.tag==subArry.count-1) {
             [bbBtn setImage:nil forState:0];
             [bbBtn setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:0];
             [bbBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 0)];
        }
        
        [self.bgView addSubview:bbBtn];
        
    }
    
   
    
    
    NSLog(@"creatBtnsList---%@",subArry);
    
}
-(void)bbBtnClick:(UIButton *)sender{
    
    if (sender.tag == self.userInfoArry.count-1) {
        return;
    }
    
    [self creatBtnsList:sender.tag];
    
    self.userInfoArry = [self.userInfoArry subarrayWithRange:NSMakeRange(0, sender.tag+1)].mutableCopy;
   self.page = 1;
   self.nowDiccInfo = self.userInfoArry.lastObject;
   [self.tableView.mj_header beginRefreshing];
//    [self requestDataDicc:self.userInfoArry.lastObject];
   
    
}
-(void)getuserShareNumberInfo{
    
    //getUserShareInfo
      NSString  * inurl = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getUserShareInfo"];
      WEAKSELF
      [[SmileHttpTool sharedInstance] POST :inurl parameters:nil origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
        STRONGSELFFor(weakSelf)
          
          if (statusCode==0) {
          NSLog(@"userGoods_getUserGoodsList----%@",responseObject);
              NSDictionary * datadicc = [NSDictionary dictionaryWithDictionary:responseObject];
              strongSelf.infoDicc = datadicc;
              dispatch_async(dispatch_get_main_queue(), ^{
                  [strongSelf changeUiData];
              });
              
          }else{
               [JMNotifyView showNotify:message isSuccessful:NO];
          }
            
          // [strongSelf stopLoadingAnimation];
          [strongSelf.tableView reloadData];
      } failure:^(id responseObject, NSError *error) {
          NSLog(@"error----%@",error);
         //  STRONGSELFFor(weakSelf)
          
          [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
          // [self stopLoadingAnimation];
      }];
    
    
    
}
-(void)changeUiData{
    
//    收益=1级返利20%
//        +2级返利15%
//        +3级返利10%
//      +4级返利5%

    NSString * Str1 = [NSString stringWithFormat:@"收益 = 1级返利%@%%",[self.infoDicc jsonString:@"oneReward"]];
    NSString * Str2 = [NSString stringWithFormat:@"    + 2级返利%@%%",[self.infoDicc jsonString:@"twoReward"]];
    NSString * Str3 = [NSString stringWithFormat:@"    + 3级返利%@%%",[self.infoDicc jsonString:@"threeReward"]];
    NSString * Str4 = [NSString stringWithFormat:@"   + 4级返利%@%%",[self.infoDicc jsonString:@"fourReward"]];
    NSString * string = [NSString stringWithFormat:@"%@%@%@%@",Str1,Str2,Str3,Str4];
    self.contentLab.text = string;
    
    [UILabel changeLineSpaceForLabel:self.contentLab WithSpace:3];
    
    
}
-(void)requestDataDicc:(NSDictionary *)userDicc{
    //getgetUserShareInfoList
   // self.nowDiccInfo = userDicc;
    [self showLoadingAnimation];
    NSString *   inurl = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getgetUserShareInfoList"];
    NSMutableDictionary * dataDicc = [NSMutableDictionary dictionary];
    [dataDicc setValue:@(self.page) forKey:@"pageNum"];
     [dataDicc setValue:@(10) forKey:@"pageSize"];
    [dataDicc setValue:@([userDicc jsonInteger:@"id"]) forKey:@"uid"];
    
    WEAKSELF
       [[SmileHttpTool sharedInstance] POST :inurl parameters:dataDicc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
               STRONGSELFFor(weakSelf)
         
            NSDictionary * dic = responseObject;
           [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            [self stopLoadingAnimation];
                 if (statusCode==0) {
                     if (self.page ==1) {
                         [self.dataSource removeAllObjects];
                     }
                      NSInteger  pages = [dic[@"pages"] integerValue];//一共多少条数据
                     NSInteger  zize = [dic[@"size"] integerValue];
                     self.tableHeaderView.numberLab.text = [NSString stringWithFormat:@"共%ld人",zize];
                     
                     
                    //  NSArray * list = dic[@"list"];//
                     NSArray * dataArry = [NSArray arrayWithArray:[responseObject jsonArray:@"list"]];
                    
                    if (weakSelf.page>pages)
                         {
                              [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                         }else
                         {
                             if (weakSelf.page > 1)
                             {
                                 [weakSelf.dataSource addObjectsFromArray:dataArry];
                                 
                             }else
                             {
                                  strongSelf.dataSource = dataArry.mutableCopy;
                             }
                         }
                 }else{
                      [JMNotifyView showNotify:message isSuccessful:NO];
                 }
           dispatch_async(dispatch_get_main_queue(), ^{
                                         [self placeholderViewWithFrame:self.tableView.frame NoNetwork:NO];
                                     });
               strongSelf.tableHeaderView.userDicc = userDicc;
               [strongSelf.tableView reloadData];
             } failure:^(id responseObject, NSError *error) {
              [self.tableView.mj_header endRefreshing];
              [self.tableView.mj_footer endRefreshing];
                 [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
                 [self stopLoadingAnimation];
             }];
    
    
    
    
}
#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 130, UIScreenWidth, UIScreenHeight  - kStatusBarAndNavigationBarHeight-130)style:UITableViewStyleGrouped];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = CELLCOLOR;
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.backgroundColor =  [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.0001)];
        [_tableView registerNib:[UINib nibWithNibName:@"ZDBRankListTableViewCell" bundle:nil]  forCellReuseIdentifier:@"ZDBRankListTableViewCell"];
    
    }
    return _tableView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZDBRankListTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"ZDBRankListTableViewCell" forIndexPath:indexPath];
   cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary * userDicc = self.dataSource[indexPath.row];
    cell.infoView.nameLab.text = [userDicc jsonString:@"nikeName"];
    //modell.nikeName;

    
    cell.infoView.numLab.text = [NSString stringWithFormat:@"%ld",indexPath.row+1];
    
    [cell.infoView.headerImage sd_setImageWithURL:[NSURL URLWithString:[userDicc jsonString:@"headImage"] ] placeholderImage:PlaceHolderImage];
    
    if (self.userInfoArry.count ==1) {
        cell.infoView.jineLab.text = [NSString stringWithFormat:@"佣金+ ¥%ld",[userDicc jsonInteger:@"sumMoney"]*[self.infoDicc jsonInteger:@"oneReward"]/100];
    }else if (self.userInfoArry.count ==2){
        // twoReward
        cell.infoView.jineLab.text = [NSString stringWithFormat:@"佣金+ ¥%ld",[userDicc jsonInteger:@"sumMoney"]*[self.infoDicc jsonInteger:@"twoReward"]/100];
    }else if (self.userInfoArry.count ==3){
        // threeReward
                       cell.infoView.jineLab.text = [NSString stringWithFormat:@"佣金+ ¥%ld",[userDicc jsonInteger:@"sumMoney"]*[self.infoDicc jsonInteger:@"threeReward"]/100];
    }else if (self.userInfoArry.count ==4){
        // fourReward
                  cell.infoView.jineLab.text = [NSString stringWithFormat:@"佣金+ ¥%ld",[userDicc jsonInteger:@"sumMoney"]*[self.infoDicc jsonInteger:@"fourReward"]/100];
    }
   
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.userInfoArry.count==4) {
        [JMNotifyView showNotify:@"用户收益最多统计到四级" isSuccessful:NO];
        return;
    }
    NSDictionary * dataDicc = self.dataSource[indexPath.row];
    NSMutableArray * userIDArry = [NSMutableArray array];
    for (NSDictionary * dataDicc2 in self.userInfoArry) {
        [userIDArry addObject:[dataDicc2 jsonString:@"id"]];
    }
    
    if ([userIDArry containsObject:[dataDicc jsonString:@"id"]]) {
        
    }else{
        [self.userInfoArry addObject:dataDicc];
    }
    
    [self creatBtnsList:self.userInfoArry.count-1];
    self.page = 1;
    self.nowDiccInfo = self.userInfoArry.lastObject;
    [self.tableView.mj_header beginRefreshing];
    //[self requestDataDicc:self.userInfoArry.lastObject];
    
}

- (void)placeholderViewWithFrame:(CGRect)frame NoNetwork:(BOOL)NoNetwork
{
    if (self.dataSource.count == 0)
    {
        [_workView removeFromSuperview];
        _workView = [[NoNetworkView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) NoNetwork:NoNetwork];
        [self.tableView addSubview:_workView];
        //_workView.centerY = self.collectionView.centerY-100;
    }else
    {
        [_workView dissmiss];
    }
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
